<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="产品名称">
            <ProductSearch :data-text="pd.queryParams.productName" :params="{isStock:true,isPurchase:true}" @ok="searchProduct1" />
          </el-form-item>
          <el-form-item label="清单名称" prop="productId">
            <el-input v-model="pd.queryParams.name" placeholder="请输入名称" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item label="更新时间" style="width: 308px">
            <el-date-picker
                v-model="pd.dateRangeUpdateTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" v-hasPermi="['wms:bom:add']" @click="handleAdd">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single" @click="handleUpdate()"
                       v-hasPermi="['wms:bom:edit']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="pd.multiple" @click="handleDelete()"
                       v-hasPermi="['wms:bom:remove']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:bom:export']">
              导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="pd.loading" :data="pd.bomList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="清单ID" align="center" prop="id" />
        <el-table-column label="清单名称" align="center" prop="name" />
        <el-table-column label="物品编码" align="center" prop="productId" />
        <el-table-column label="物品名称" align="center" prop="productName" />
        <el-table-column label="是否启用" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.status ? '1' : '0' "/>
          </template>
        </el-table-column>
        <el-table-column label="创建部门" align="center" prop="createDept"/>
        <el-table-column label="备注" align="center" prop="remark"/>
        <el-table-column label="创建者" align="center" prop="createBy"/>
        <el-table-column label="创建时间" align="center" prop="createTime"/>
        <el-table-column label="更新者" align="center" prop="updateBy"/>
        <el-table-column label="更新时间" align="center" prop="updateTime"/>
        <el-table-column width="160" fixed="left" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['wms:bom:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['wms:bom:remove']">删除</el-button>
            <el-button link type="primary" icon="Tickets" @click="navigationBomLine(scope.row)"
                       v-hasPermi="['wms:bom:remove']">物料</el-button>
              <el-button link type="primary" icon="Setting" @click="navigation(scope.row)">工艺</el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList"/>
    </el-card>
    <!--     添加或修改测试主从对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="700px" append-to-body>
      <el-form ref="bomFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="物品编码" prop="productId">
              <ProductSearch :params="{isStock:true,isProduce:true}" :dataText="pd.form.productName" @ok="searchProduct2" />
            </el-form-item>
            <el-form-item label="耗时(/m)" prop="costTime">
              <el-input v-model="pd.form.costTime" placeholder="请输入单个物品完成耗时(单位：秒)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="清单名称" prop="name">
              <el-input v-model="pd.form.name" placeholder="请输入清单名称" />
            </el-form-item>
            <el-form-item label="是否启用" prop="status">
              <el-select v-model="pd.form.status" placeholder="请输入是否启用">
                <el-option
                  v-for="(item, index) in pd.bomSelect"
                  :key="index"
                  :label="item"
                  :value="index"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="pd.dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<!--物料清单-->
<script setup name="Bom" lang="ts">
import {BomVO, listBom, addBom, delBom, updateBom, getBom} from "@/views/wms/bom/api";
import ProductSearch from '@/views/wms/product/search.vue'
import {ProductVO, listProduct} from "@/views/wms/product/api";

const router = useRouter();
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const bomFormRef = ref()
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no' ));

const pd = reactive({
  bomList: <BomVO[]>([]),
  productList: <ProductVO[]>([]),
  dateRangeUpdateTime: <[DateModelType, DateModelType]>(['', '']),
  buttonLoading: false,
  bomSelect: {1: '停用', 0: '正常'},
  loading: true,
  showSearch: true,
  ids: <Array<number>>([]),
  productIds: <Array<number>>([]),
  single: true,
  multiple: true,
  total: 0,
  form: <BomVO>{},
  dialog: <DialogOption>{
    visible: false,
    title: ''
  },
  queryParams: <BomVO>{
    pageNum: 1,
    pageSize: 10,
    productId: undefined,
    params: {
      updateTime: undefined,
    }
  },
  rules: <ElFormRules>{
    productId: [{required: true, message: "物品不能为空", trigger: "blur"}],
  }
})

/** 查询测试主从列表 */
async function getList() {
  pd.loading = true;
  const result = await listProduct();
  pd.productList = result.rows;
  pd.queryParams.params = {};
  proxy?.addDateRange(pd.queryParams, pd.dateRangeUpdateTime, 'UpdateTime');
  const res = await listBom(pd.queryParams);
  pd.bomList = res.rows;
  pd.total = res.total;
  pd.loading = false;
}

function navigation(scope:BomVO){
  router.push({
    path: '/wms/bom/process',
    query:{
      id:scope.id,
    }
  })
}
function navigationBomLine(scope:BomVO){
  console.log(scope.name)
  router.push({
    path: '/wms/bom/line',
    query:{
      id:scope.id,
      productId:scope.productId,
      bomName:scope.name
    }
  })
}

function searchProduct1(value: ProductVO[]) {
  pd.queryParams.productId = value[0].id as number;
  pd.queryParams.productName = value[0].name;
}

function searchProduct2(value: ProductVO[]) {
  pd.form.productId = value[0].id as number;
  pd.form.productName = value[0].name;
}

/** 多选框选中数据 */
function handleSelectionChange(selection: BomVO[]) {
  pd.ids  = selection.map(item => item.id) as Array<number>;
  pd.productIds  = selection.map(item => item.productId) as Array<number>;
  pd.single = selection.length != 1;
  pd.multiple = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  pd.form.status = '0';
  pd.dialog.visible = true;
  pd.dialog.title = "新增物料清单";
}

/** 修改按钮操作 */
async function handleUpdate(row?: BomVO) {
  reset();
  const _id = row?.id || pd.ids[0];
  const res = await getBom(_id);
  Object.assign(pd.form, res.data);
  pd.form.productName = row?.productName;
  pd.dialog.visible = true;
  pd.dialog.title = "修改物料清单";
}

/** 删除按钮操作 */
async function handleDelete(row?: BomVO) {
  const productIds = row?.productId || pd.productIds;
  const _ids = row?.id || pd.ids;
  await proxy?.$modal.confirm('是否确认删除物品编码为"' + productIds + '"的数据项？').finally(() => pd.loading = false);
  await delBom(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 提交表单 */
function submitForm() {
  bomFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateBom(pd.form).finally(() => {
          proxy?.$modal.msgSuccess("修改成功");
          pd.buttonLoading = false;
        });
      } else {
        await addBom(pd.form).finally(() => {
          proxy?.$modal.msgSuccess("新增成功");
          pd.buttonLoading = false;
        });
      }
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 表单重置 */
function reset() {
  pd.form = {
    productId: undefined,
    status: '',
    createDept: undefined,
    remark: '',
    productName: '',
  };
  pd.queryParams.productName = '';
  bomFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  pd.dateRangeUpdateTime = ['', ''];
  (proxy?.$refs['queryFormRef'] as any).resetFields();
  pd.queryParams.productName = '';
  handleQuery();
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/bom/export', {
    ...pd.queryParams
  }, `bom_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>

<style scoped>
</style>
